//
//  AppUpdateView.m
//  ebook
//
//  Created by ChenNan on 16/6/7.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "AppUpdateView.h"
#import "EbookNetRequest.h"

#define kTitleHeight 60      //title字体高度
#define kTitleFontSize 21    //title字体大小
#define kspaceV 10           //间隔高度
#define kTextViewFontSize 16 //内容字体大小
#define kUpdateBtnWidth 120  //按钮高度
#define kUpdateBtnHeight 40  //按钮宽度

#define kUpdataviewTag 99

@interface AppUpdateView ()<UITextViewDelegate>

@property (nonatomic, copy) NSString *openUrl;
@property (nonatomic, strong) __block NSDictionary *dictData;
@property (nonatomic, strong) UIViewController *controller;

@end

@implementation AppUpdateView

+(void)showAppUpdateInController:(UIViewController *)controller{
    AppUpdateView *view = [[AppUpdateView alloc] initWithController:controller];
    [view getUpdateData:^{
        [view show];
    }];
}

- (instancetype)initWithController:(UIViewController *)controller {
    
    if (self = [super initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH)]) {
        self.backgroundColor = MTColor(85, 85, 85, 0.7);
        self.tag = kUpdataviewTag;
        _controller = controller;
    }
    return self;
}

- (void)show{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self drawView];
        if ([self compareVersion]) {
            [self fadeIn];
        }
    });
}

- (void)getUpdateData:(void(^)(void))complete {
    
    [EbookNetRequest applicationGetVersionDataSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        _dictData = dict[@"data"];
        if(complete&&dict)complete();
    } failed:^(int stateCode, NSString *failMsg) {
    }];
}

- (BOOL)compareVersion {
    
    //服务器返回的版本号
    NSString *serverVersion = [_dictData objectForKey:@"version"];
    
    //本地版本号
    NSString*currentVersion=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if ([serverVersion floatValue]>[currentVersion floatValue]) {
        return YES;
    }
    return NO;
}

- (BOOL)isForceUpdate {
    
    return [[_dictData objectForKey:@"isforceupdate"] boolValue];
}

- (void)drawView {
    
    NSString *content = [_dictData objectForKey:@"content"];
    _openUrl = [_dictData objectForKey:@"downurl"];
    
    CGSize size = CGSizeMake(260, 190);
    
    UIColor *color = MTConfigColor(@"MTNavigationBar_background_Color");
    //背景
    UIView *backgroundView = [[UIView alloc] init];
    CGFloat fHeight = kTitleHeight+kspaceV+size.height+kspaceV+kUpdateBtnHeight+kspaceV+20;
    backgroundView.frame = CGRectMake(MTScreenW/2 - size.width/2, 0, size.width, fHeight);
    backgroundView.y = (MTScreenH-backgroundView.height)/2;
    backgroundView.backgroundColor = [UIColor whiteColor];
    backgroundView.layer.cornerRadius = 7;
    backgroundView.layer.masksToBounds = YES;
    [self addSubview:backgroundView];
    /**
     *  closeBtn 红色按钮  只负责显示，没有点击
     *  containCloseBtn   透明盖在closeBtn上，负责点击
     */
    //关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *closeImg = [UIImage imageNamed:@"updateColse"];
    closeBtn.frame = CGRectMake(CGRectGetMaxX(backgroundView.frame)-closeImg.size.width/4-12, CGRectGetMinY(backgroundView.frame)-closeImg.size.height+closeImg.size.height/4+12, closeImg.size.width, closeImg.size.height);
    [closeBtn setImage:closeImg forState:UIControlStateNormal];
    closeBtn.alpha = 1;
    
    UIButton *containCloseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    containCloseBtn.frame = CGRectMake(CGRectGetMinX(closeBtn.frame)-5, CGRectGetMinY(closeBtn.frame)-5, 45, 45);
    containCloseBtn.tag = 2;
    [containCloseBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //标题
    UILabel *headLabel = [[UILabel alloc] init];
    headLabel.frame = CGRectMake(0, 0, backgroundView.width, kTitleHeight);
    headLabel.backgroundColor = color;
    headLabel.font = [UIFont systemFontOfSize:kTitleFontSize];
    headLabel.text = [_dictData objectForKey:@"title"];
    headLabel.textColor = [UIColor whiteColor];
    headLabel.textAlignment = NSTextAlignmentCenter;
    [backgroundView addSubview:headLabel];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:headLabel.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(0, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = headLabel.bounds;
    maskLayer.path = maskPath.CGPath;
    headLabel.layer.mask = maskLayer;
    
    NSMutableAttributedString *attributeStr = [self formatString:content];
    //内容
    UITextView *textView = [[UITextView alloc] init];
    textView.frame = CGRectMake(20, CGRectGetMaxY(headLabel.frame)+kspaceV, backgroundView.width-40, size.height+20);
    textView.attributedText = attributeStr;
    textView.editable = NO;
    textView.delegate = self;
    [backgroundView addSubview:textView];
    
    //更新按钮
    UIButton *updateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    updateBtn.frame = CGRectMake(backgroundView.width/2 - kUpdateBtnWidth/2, CGRectGetMaxY(textView.frame)+kspaceV, kUpdateBtnWidth, kUpdateBtnHeight);
    [updateBtn setTitle:@"立即更新" forState:UIControlStateNormal];
    [updateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    updateBtn.tag = 1;
    updateBtn.backgroundColor = color;
    updateBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [updateBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:updateBtn];
    
    if (![self isForceUpdate]) {
        [self addSubview:closeBtn];
        [self addSubview:containCloseBtn];
    }
}

#pragma mark - textView点击没有复制功能
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    return NO;
}

#pragma mark - 字符串操作
-(NSMutableAttributedString *)formatString:(NSString *)string {
    
    string = [string stringByReplacingOccurrencesOfString:@"#" withString:@"#● "];
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] init];
    
    NSMutableArray *array = (NSMutableArray*)[string componentsSeparatedByString:@"#"];
    [array removeObjectAtIndex:0];
    for (NSString *str in array) {
        [AttributedStr appendAttributedString:[self stringColorWithString:str]];
    }
    return AttributedStr;
}

- (NSAttributedString *)stringColorWithString:(NSString *)str {
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:str];
    [AttributedStr addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:kTextViewFontSize]
                          range:NSMakeRange(0, str.length)];
    [AttributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor grayColor]
                          range:NSMakeRange(0, str.length)];
    if ([str hasPrefix:@"●"]) {
        [AttributedStr addAttribute:NSForegroundColorAttributeName
                              value:MTConfigColor(@"MTNavigationBar_background_Color")
                              range:NSMakeRange(0, 1)];
    }
    return AttributedStr;
}

#pragma mark - 按钮点击事件
- (void)btnClick:(UIButton *)btn {
    
    NSURL *url  = [NSURL  URLWithString:_openUrl];
    if(btn.tag==1)
        [[UIApplication sharedApplication] openURL:url];
    [self fadeOut];
}

- (void)fadeIn {
    
    [UIView animateWithDuration:0 animations:^{} completion:^(BOOL finished) {
        
        CATransition *transition =[CATransition animation];
        [transition setDuration:.5];
        [transition setType:kCATransitionReveal];
        [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
        [self.layer addAnimation:transition forKey:kCATransitionReveal];
        
        UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
        if(![keywindow viewWithTag:kUpdataviewTag])//防止重复更新提示框弹出
            [keywindow addSubview:self];
    }];
}

- (void)fadeOut {
    
    [UIView animateWithDuration:.35 animations:^{
        self.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}

@end
